﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Collections;

namespace ChaoDaoOs2
{
    public partial class frmMain : Form
    {
        DllClass.SensorInfo sendorinfo;
        DllClass.IS1Info is1Info;
        private HttpClient os2_client = new HttpClient();
        WriteLog writeLog = new WriteLog();
        string[] WeithUnit = new string[]{"公克","公斤","公吨","分(香港)","钱(香港)","两(香港)","斤(香港)",
                              "担(香港)","分(台湾)","钱(台湾)","两(台湾)","斤(台湾)","担(台湾)","盎司","磅","千磅"};

        public frmMain()
        {
            InitializeComponent();
        }

        private void AddOS2WeightPlugin()
        {
            var isOk = OS2WeightService.Init("1", weight =>
            {
                MessageBox.Show(weight);
            }, 1);

        }

        #region "DLL处理请求和响应"

        //double NetWeight: 净重
        //double Tare: 皮重
        //double Grossweight: 毛重
        //int Mode: 模式
        //int DecimalDigit: 小数位数
        //int UnitChar: 重量单位
        //int OldAd, int FilterAd, int ZeroAd, int WeightAd: 保留
        //int flag:
        //   Bit0: 0表示重量不稳定            1表示重量稳定
        //   Bit1: 0表示重量没有溢出          1表示重量溢出
        //   Bit2: 0表示有开机归零            1表示没有开机归零
        //   Bit3: 0当前重量大于最小称量范围  1当前重量小于最小称量范围
        //   Bit4: 1当前OP盒被软解锁         0当前OP盒没有软解锁
        //   Bit5: 1当前OP盒硬件解锁         0当前OP盒硬件没解锁
        //   Bit6: 1结果的最低位永远为零		  0结果的最低位可能非零
        public void DisplaySensorInfo(double NetWeight, double Tare, double Grossweight, int Mode, int DecimalDigit, int UnitChar,
                             int OldAd, int FilterAd, int ZeroAd, int WeightAd, int flag)
        {
            int flagMode = 0;
            string sfor = "";
            string unitval = WeithUnit[UnitChar];


            sfor = ""; // "C" + DecimalDigit.ToString();

            if ((flag & 0x01) != 0x01)
            {
                //重量不稳定
                status1.Text = "重量不稳定";
            }
            else
            {
                //重量稳定
                status1.Text = "重量稳定";
            }

            if ((flag & 0x02) == 0x02)
            {
                flagMode = 0xFF;
                //重量溢出
                status2.Text = "重量溢出";
            }
            else
            {
                //重量正常
                status2.Text = "重量正常";
            }

            if ((flag & 0x04) == 0x04)
            {
                //没有开机归零
                status3.Text = "没有开机归零";
            }
            else
            {
                //开机归零
                status3.Text = "开机归零";
            }

            if ((flag & 0x08) == 0x08)
            {
                //当前重量小于最小称量范围
                status4.Text = "当前重量小于最小称量范围";
            }
            else
            {
                //当前重量大于最小称量范围
                status4.Text = "当前重量大于最小称量范围";
            }

            if ((flag & 0x10) == 0x10)
            {
                //当前OP盒被软解锁
                status5.Text = "当前OP盒被软解锁";
            }
            else
            {
                //当前OP盒没有软解锁
                status5.Text = "当前OP盒没有软解锁";
            }

            if ((flag & 0x20) == 0x20)
            {
                //当前OP盒硬件解锁
                status6.Text = "当前OP盒硬件解锁";
            }
            else
            {
                //当前OP盒硬件没解锁
                status6.Text = "当前OP盒硬件没解锁";
            }

            if ((flag & 0x40) == 0x40)
            {
                //结果的最低位永远为零
                status7.Text = "结果的最低位永远为零";
            }
            else
            {
                //结果的最低位可能非零
                status7.Text = "结果的最低位可能非零";
            }

            switch (Mode)
            {
                case 0:
                    {
                        weightlbl.Text = NetWeight.ToString(sfor) + " " + unitval;
                        Tarelbl.Text = "0.00";
                        Grossweightlbl.Text = "0.00";
                        break;
                    }
                case 1:
                case 2:
                    {
                        weightlbl.Text = NetWeight.ToString(sfor) + " " + unitval;
                        Tarelbl.Text = Tare.ToString(sfor) + " " + unitval;
                        Grossweightlbl.Text = Grossweight.ToString(sfor) + " " + unitval;
                        if (Mode == 2)
                        {
                            label4.Text = "预制皮重:";
                        }
                        else
                        {
                            label4.Text = "皮重:";
                        }
                        break;
                    }
            }


            if (flagMode == 0xFF)
            {
                weightlbl.Text = "-----";
                Tarelbl.Text = "-----";
                Grossweightlbl.Text = "-----";

            }

        }

        public void DisplayIS1Info(string status, string sign, string Weight, string fUnit, int flag)
        {
            string fstatus, fweight, oweight;
            fstatus = status;
            if (fstatus == "F")
            {
                label6.Text = "重量溢出或没有开机归零";
            }
            if (fstatus == "S")
            {
                label6.Text = "重量稳定";
            }
            if (fstatus == "U")
            {
                label6.Text = "重量不稳定";
            }

            string realweight;
            realweight = sign + Weight;

            oweight = Weight;
            fweight = sign;
            fweight = fweight + Weight;
            fweight = fweight + fUnit;

            label7.Text = fweight.Trim();

            if (fstatus == "F")
            {
                label7.Text = "---------------";
            }
            //重量稳定
            if (fstatus == "S")
            {
                //调用API接口写一个重量JSON格式至服务器
                decimal weight = decimal.Parse(realweight) * 1000;
                //writeLog.WriteLogInfo(weight.ToString());
                //log.Text = log.Text + "\r\n" + "获取重量：" + weight.ToString();
                //postWeight(weight.ToString());
                SendPostRequestAsync(weight.ToString());
            }
        }

        #endregion 
        private async Task postWeight(string weight)
        {
            try
            {
                // 设置目标URL和JSON数据
                string url = "https://chaodao.hnhckj.com.cn/cashier/storeapi/login/weightwrite";
                System.Collections.Specialized.NameValueCollection namevalue2 = new System.Collections.Specialized.NameValueCollection();
                namevalue2["weight"] = weight.ToString();
                namevalue2["store_id"] = this.txtStore_id.Text.Trim();
                namevalue2["client_id"] = this.txtClient_id.Text.Trim();
                PostData(url, namevalue2);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //writeLog.WriteLogInfo(ex.Message);
                //log.Text = log.Text + "\r\n" + "添加重量数据至服务器错误：" + ex.Message;
            }
        }

        private async Task SendPostRequestAsync(string weight)
        {
            System.Net.ServicePointManager.Expect100Continue = true;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;

            var url = "https://chaodao.hnhckj.com.cn/cashier/storeapi/login/weightwrite"; // API URL
            try
            {
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("weight", weight.ToString()), // 替换为你的参数和值
                    new KeyValuePair<string, string>("store_id", this.txtStore_id.Text.Trim()),
                    new KeyValuePair<string, string>("client_id", this.txtClient_id.Text.Trim())
                });
                HttpResponseMessage response = await os2_client.PostAsync(url, content); // 发送POST请求
                string result = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                writeLog.WriteLogInfo(ex.Message);
            }
        }

        public string PostData(string url, NameValueCollection namevalue)
        {
            string responseData = "";
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // 或者使用 Tls | Tls11 | Tls12 | Tls13 等组合

                using (var client = new WebClient())
                {
                    byte[] bytes = client.UploadValues(url, namevalue);
                    responseData = Encoding.UTF8.GetString(bytes);
                    //log.Text = log.Text + "\r\n" + "添加重量数据：" + responseData.ToString();
                    writeLog.WriteLogInfo(responseData.ToString());
                }
            }
            catch (Exception ex)
            {
                //writeLog.WriteLogInfo(ex.Message);
                //log.Text = log.Text + "\r\n" + "添加服务器出错：" + ex.Message;
                Console.WriteLine(ex.Message);
            }
            return responseData;
        }

        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            //为了通过证书验证，总是返回true
            return true;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.comboBox3.SelectedIndex = 0;
            this.comboBox4.SelectedIndex = 0;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            sendorinfo = DisplaySensorInfo;
            DllClass.__SetCallBackFunc("SENSORINFO", sendorinfo);
            is1Info = DisplayIS1Info;
            DllClass.__SetCallBackFunc("IS1INFO", is1Info);

            string cname = comboBox1.Text;
            int brate = Convert.ToInt32(comboBox2.Text);
            bool ret = DllClass.__Open(cname, brate);
            if (ret)
            {
                log.Text = log.Text + "串口打开成功";

            }
            else
            {
                log.Text = log.Text + "串口打开失败";
            }
            button1_Click(null, null);
            button4_Click(null, null);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (DllClass.__Close())
            {
                log.Text = log.Text + "串口关闭成功";
            }
            else
            {
                log.Text = log.Text + "串口关闭失败";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UInt16 val = (UInt16)(comboBox3.SelectedIndex + 1);
            if ((val == 1) | (val == 2) | (val == 3))
            {
                DllClass.__ChangeProtocol(val);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            UInt16 val = (UInt16)(comboBox4.SelectedIndex);
            DllClass.__SetUnitValue(val, "1234");
        }

        private void btnGetWeight_Click(object sender, EventArgs e)
        {
            var result = DllClass.__udeWeight();
            MessageBox.Show(result);
            StringBuilder sRet = new StringBuilder(256);
            bool bRet = DllClass.__GetWeightEx(ref sRet);
            log.Text = log.Text + "\r\n" + sRet.ToString();
            //log.Text = log.Text + "\r\n"+DllClass.__GetWeight();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DllClass.__Weight("1234");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DllClass.__udeWeight();
        }
    }


}
